using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Lab4Shadows
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        private GraphicsDeviceManager m_graphics;
        private SpriteBatch m_spriteBatch;

        private Matrix World;
        private Matrix View;
        private Matrix Projection;

        private Effect Effects;
        private Vector3 CameraPosition = new Vector3(0.0f, 2.0f, 4.0f);
        private double FieldOfView = 70.0;

        private Model ModelToDraw;

        private VertexBuffer m_vertexBuffer;

        private IndexBuffer m_indexBuffer;

        public Game1()
        {
            m_graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            m_graphics.PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            m_spriteBatch = new SpriteBatch(GraphicsDevice);

            // Load Content.
            Effects = Content.Load<Effect>("Effects/Effect1");
            ModelToDraw = Content.Load<Model>("Models/Sphere");

            // Remap models.
            RemapModel(ModelToDraw, Effects);

            // Load the techniques.
            Effects.CurrentTechnique = Effects.Techniques["Technique1"];

            m_vertexBuffer = new VertexBuffer(m_graphics.GraphicsDevice, typeof(VertexPositionNormalTexture), 4, BufferUsage.None);
            VertexPositionNormalTexture[] vdata = new VertexPositionNormalTexture[4];
            vdata[0].Position = new Vector3(-1.0f, -1.0f, 0.0f);
            vdata[0].Normal = new Vector3(0.0f, 0.0f, 1.0f);
            vdata[0].TextureCoordinate = new Vector2(0.0f, 1.0f);

            vdata[1].Position = new Vector3(-1.0f, 1.0f, 0.0f);
            vdata[1].Normal = new Vector3(0.0f, 0.0f, 1.0f);
            vdata[1].TextureCoordinate = new Vector2(0.0f, 0.0f);

            vdata[2].Position = new Vector3(1.0f, -1.0f, 0.0f);
            vdata[2].Normal = new Vector3(0.0f, 0.0f, 1.0f);
            vdata[2].TextureCoordinate = new Vector2(1.0f, 1.0f);

            vdata[3].Position = new Vector3(1.0f, 1.0f, 0.0f);
            vdata[3].Normal = new Vector3(0.0f, 0.0f, 1.0f);
            vdata[3].TextureCoordinate = new Vector2(1.0f, 0.0f);

            m_vertexBuffer.SetData<VertexPositionNormalTexture>(vdata);

            short[] indexList = new short[6] { 0, 1, 2, 2, 1, 3 };

            m_indexBuffer = new IndexBuffer(m_graphics.GraphicsDevice, IndexElementSize.SixteenBits, 6, BufferUsage.None);
            m_indexBuffer.SetData<short>(indexList);
        }

        /// <summary>
        /// Call this method to remap the model.
        /// </summary>
        /// <param name="a_model">The model to remap.</param>
        /// <param name="a_effect">The effect to be used by the model.</param>
        private static void RemapModel(Model a_model, Effect a_effect)
        {
            foreach (ModelMesh mesh in a_model.Meshes)
            {
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    part.Effect = a_effect;
                }
            }
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="a_gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime a_gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape) == true)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(a_gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="a_gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime a_gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            DrawModel(a_gameTime);

            base.Draw(a_gameTime);
        }

        /// <summary>
        /// This is called to draw a model.
        /// </summary>
        /// <param name="a_gameTime">Provides a snapshot of timing values.</param>
        private void DrawModel(GameTime a_gameTime)
        {
            // Set the matrix values.
            World = Matrix.CreateScale(2.5f) * Matrix.CreateRotationX((float)(Math.PI * -90.0 / 180.0)) * Matrix.CreateTranslation(0.0f, 0.0f, 0.0f);
            View = Matrix.CreateLookAt(CameraPosition, Vector3.Zero, Vector3.Up);
            Projection = Matrix.CreatePerspectiveFieldOfView((float)(Math.PI * FieldOfView / 180.0f), GraphicsDevice.Viewport.AspectRatio, 2.0f, 10.0f);

            // Set effect parameters.
            Effects.Parameters["World"].SetValue(World);
            Effects.Parameters["View"].SetValue(View);
            Effects.Parameters["Projection"].SetValue(Projection);
            Effects.Parameters["LightPos"].SetValue(new Vector3(10, 10, 10));
            Effects.Parameters["ModelColor"].SetValue(new Vector4(0.5f, 0.5f, 0.5f, 1.0f));
            Effects.Parameters["bias"].SetValue(0.0f);

            m_graphics.GraphicsDevice.SetVertexBuffer(m_vertexBuffer);
            m_graphics.GraphicsDevice.Indices = m_indexBuffer;

            // Clear stencil buffer to zero.
            m_graphics.GraphicsDevice.Clear(ClearOptions.Stencil, Color.Black, 0, 0);
            DepthStencilState state = new DepthStencilState();
            state.StencilEnable = true;
            state.StencilFunction = CompareFunction.Always;
            state.StencilPass = StencilOperation.Increment;
            m_graphics.GraphicsDevice.DepthStencilState = state;

            foreach (EffectPass pass in Effects.CurrentTechnique.Passes)
            {
                pass.Apply();
                m_graphics.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 4, 0, 2);
            }

            World = Matrix.CreateTranslation(0.0f, 1.0f, 0.0f);
            Effects.Parameters["World"].SetValue(World);
            DrawMesh(ModelToDraw);

            // Set up alpha blending to make the shadow semi-transparent.
            m_graphics.GraphicsDevice.BlendState = BlendState.AlphaBlend;

            Matrix shadowproj = new Matrix(10.0f, 0.0f, 0.0f, 0.0f,
                                           -10.0f, 0.0f, -10.0f, -1.0f,
                                           0.0f, 0.0f, 10.0f, 0.0f,
                                           0.0f, 0.0f, 0.0f, 10.0f);

            World = Matrix.CreateTranslation(0.0f, 1.0f, 0.0f) * shadowproj;

            Effects.Parameters["World"].SetValue(World);
            Effects.Parameters["bias"].SetValue(0.001f);
            DepthStencilState state2 = new DepthStencilState();
            state2.StencilEnable = true;
            state2.StencilFunction = CompareFunction.LessEqual;
            state2.StencilPass = StencilOperation.Increment;
            m_graphics.GraphicsDevice.DepthStencilState = state2;

            // Draw on the screen if 1 is the stencil buffer value.
            m_graphics.GraphicsDevice.ReferenceStencil = 1;

            DrawMesh(ModelToDraw);

            m_graphics.GraphicsDevice.BlendState = BlendState.Opaque;
        }

        /// <summary>
        /// This is called to draw out a model that contains a mesh.
        /// </summary>
        /// <param name="a_model">Provides the model to be drawn.</param>
        private void DrawMesh(Model a_model)
        {
            foreach (ModelMesh mesh in a_model.Meshes)
            {
                foreach (Effect e in mesh.Effects)
                {
                    mesh.Draw();
                }
            }
        }
    }
}
